package com.flick.base.service;

import com.flick.base.dao.BaseRepository;
import com.flick.base.dao.Myspec;
import com.flick.common.Filters;
import com.flick.common.Page;
import com.flick.common.PageParam;
import com.flick.util.IteratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * Created by flick on 2017/4/23.
 */
public abstract class QueryServ<T,DAO extends BaseRepository> {

    @Autowired
    DAO dao;

    public List<T> list(Filters filters) throws Exception{
        Specification<T> sc = new Myspec<T>(filters);

        return (List<T>) dao.findAll(sc);
    }

    public Page page(PageParam pageParam) throws Exception{
        Filters filters = pageParam.getFilters();
        Specification<T> sc = new Myspec(filters);
        String sidx = pageParam.getSidx();
        String sord = pageParam.getSord();
        PageRequest pageRequest;
        if(sidx != null && sord != null){
            Sort sort;
            if(sord.equals("desc"))
                sort = new Sort(Sort.Direction.DESC,sidx);
            else
                sort = new Sort(Sort.Direction.ASC,sidx);
            pageRequest = new PageRequest(pageParam.getPageNum()-1,pageParam.getPageSize(),sort);

        }else
            pageRequest = new PageRequest(pageParam.getPageNum()-1,pageParam.getPageSize());
        org.springframework.data.domain.Page dataPage = dao.findAll(sc,pageRequest);
        Page<T> page = new Page<T>();
        page.setCount(dataPage.getTotalElements());
        page.setMaxPage(dataPage.getTotalPages());
        page.setPageNum(dataPage.getNumber()+1);
        page.setPageSize(dataPage.getSize());
        page.setObjList(dataPage.getContent());
        return page;

    }
    public T get(String id) throws Exception{
        return (T)dao.findOne(id);
    }


}
